package com.JZ.QM.service.impl;

import com.JZ.QM.common.dao.UserAccountDao;
import com.JZ.QM.common.entity.UserAccountEntity;
import com.JZ.QM.common.utils.PageUtils;
import com.JZ.QM.common.utils.Query;
import com.JZ.QM.service.UserAccountService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jcajce.provider.keystore.BC;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @author: cyc
 * @email cyc@gmail.com
 * @date: 2020/6/26 18:06
 */
@Slf4j
@Service()
public class UserAccountServiceImpl extends ServiceImpl<UserAccountDao,UserAccountEntity> implements UserAccountService {
    @Resource
    UserAccountDao userAccountDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) throws Exception {
        IPage<UserAccountEntity> page = this.page(
                new Query<UserAccountEntity>().getPage(params),
                new QueryWrapper<UserAccountEntity>()
        );
        return new PageUtils(page);
    }

    /**
     * 通过用户id获取用户的账号id
     * @param userId 用户id
     * @return
     */
    @Override
    public UserAccountEntity getAccount(Long userId) {
        //条件构造器
        QueryWrapper queryWrapper=new QueryWrapper();
        //账户基本信息
        UserAccountEntity userAccountEntity=new UserAccountEntity();

        queryWrapper.eq("user_id",userId);
        //获取账户的id
        userAccountEntity=userAccountDao.selectOne(queryWrapper);
        return userAccountEntity;

    }

    /**
     * 开通用户平台账户
     * @param userId 用户的id
     * @param userPassword 用户设置的平台密码
     * @return
     */
    @Transactional
    @Override
    public boolean openUserAccount(Long userId, String userPassword) {
        //密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        //用户账号基本信息
        UserAccountEntity userAccountEntity=new UserAccountEntity();
        //影响的行数
        int affectRow=-1;
        userAccountEntity.setUserId(userId);
        userAccountEntity.setUserPassword(bCryptPasswordEncoder.encode(userPassword));
        userAccountEntity.setAccountAmoount(new BigDecimal(0));
        affectRow=userAccountDao.insert(userAccountEntity);
        if(affectRow>0){
            return true;
        } else {
            return false;
        }
    }
}
